<template>
	<div class="alertBox addGiftBox">
		<div class="alertBk"></div>
		<div class="wordBox">
			<div class="alertHead">
				<p class="tittle" v-text="title"></p>
				<div class="myClose" @click="closeAddGift">
					<img src="~_assets/close.png" class="myClose" />
				</div>
			</div>
			<div class="alertBody">
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>奖项名称:</p>
					<input maxlength=30 :disabled="isDetail" type="text" class="alertInput" placeholder="请输入奖项名称" v-model.trim="giftsName"/>
					<span class="checkTxt" v-show="diffGiftsName" v-text="diffText" style="right:11%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>礼品图片:</p>
					<div class="addImg">
						<el-upload
							class="newAct"
							:disabled="isDetail"	
							:limit="1"
							:show-file-list='false'
							:action="picUpload"
							:data="picData"
							ref="homeImg"
							:on-success="homeImgSuccess"
							:before-upload="beforeAvatarUpload">
							<img v-if="homeImageUrl" :src="PIC_URL+homeImageUrl" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</div>
					<span class="checkTxt" v-show="diffHomeImg" v-text="diffText" style="right:55%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>单次发放:</p>
					<el-input v-model.trim="singleIssue" class="setInput" :disabled="isDetail" maxlength="2">
					</el-input>
					<p class="unit">张</p>
					<span class="checkTxt" v-show="diffIsSingleIssue" v-text="diffText" style="right:44%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>投放数量:</p>
					<el-checkbox v-model="isLimitNum" :disabled="isDetail">限制</el-checkbox>
					<el-input @blur="checkNum($event,5,0,10)" :disabled="isDetail || !isLimitNum" placeholder="" v-model.trim="prizePutNumber" class="setInput" clearable maxlength="5">
					</el-input>
					<p class="unit">张</p>
					<span class="checkTxt" v-show="diffIsLimitNum" v-text="diffText" style="right:38%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>中奖概率:</p>
					<el-input :disabled="isDetail" placeholder="" v-model.trim="winningProbability" class="setInput" clearable maxlength="6">
					</el-input>/100000
					<span class="checkTxt" v-show="diffWin" v-text="diffText" style="right:47%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>赠送次数:</p>
					<el-radio v-model="giveLimitType" label="0" :disabled="isDetail">不限</el-radio>
					<el-radio v-model="giveLimitType" :label="value2" :disabled="isDetail">限制</el-radio>
					<el-select v-model="value2" class="setSelect" :disabled="canGiveLimitType">
						<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
					<el-input @blur="checkNum($event,2,0,1)" placeholder="" :disabled="isDetail || canGiveLimitType" v-model.trim="giveFrequencyLimit" class="setInput" clearable>
					</el-input>
					<p class="unit">次</p>
					<span class="checkTxt" v-show="diffGiveLimitType" v-text="diffText" style="right:8%" ></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>有效期限:</p>
					<!-- <el-checkbox v-model="iselectDate">日期</el-checkbox> -->
					<el-date-picker placeholder="选择日期" :disabled="isDetail" value-format="yyyy-MM-dd" v-model="receiveDeadline" type="date" align="right" :picker-options="pickerOptions0" style="margin-left: 0.08rem;">
					</el-date-picker>
					<span class="checkTxt" v-show="diffDeadline" v-text="diffText" style="right:41%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText"><sup>*</sup>领取地址:</p>
					<input :disabled="isDetail" type="text" class="alertInput" placeholder="请输入领取地址" v-model.trim="receiveAddress" maxlength="30"/>
					<span class="checkTxt" v-show="diffAddress" v-text="diffText" style="right:11%"></span>
				</div>
				<div class="changeDiv">
					<p class="alertText">备注:</p>
					<el-input maxlength=100 :disabled="isDetail" type="textarea" autosize placeholder="请输入内容" v-model.trim="notes">
					</el-input>
					<span class="checkTxt" v-show="diffNotes" v-text="diffText" style="right:1%"></span>
				</div>
				<div class="alertBut">
					<button class="isFalse" @click="closeAddGift(0)">取消</button>
					<button class="isTrue" @click="closeAddGift(1)" v-show="!isDetail">确认</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { time } from '_config/common.js'
	import {ADD_GIFTS,FILE_UPLOAD,FIND_GIFTS_BY_ID,UPDATE_GIFTS} from '@/config/url'
	import Bus from '@/bus.js'
	import { publicVM } from "_config/public.js";

	export default {
		mixins: [publicVM],
		props:['prizeID','leng','giftID','btnType','firstID','pos'],
		data() {
			return {
				pickerOptions0: {
					disabledDate(time) {
					return time.getTime() < Date.now() - 8.64e7;
					}
				},
				value2: '1',
				send: '',
				options2: [
					{
						value: '1',
						label: '活动周期'
					},
					{
						value: '2',
						label: '每日'
					},
				],
				activityCode:sessionStorage.getItem('activityCode'),//活动code
				giftsName:null,//礼品名称
				giftsPicturesUrl:null,//礼品图片的路径
				prizePutNumber:'0',//奖品投放数量：0 表示不限制，0之上表示限制的数量
				winningProbability:'10000',//中奖率
				singleIssue: '',//单次发放
				giveFrequencyLimit:'0',//是否限制赠送次数：0 不限，0之上限制的次数
				giveLimitType:'0',//赠送次数限制的类型：0 不限，1 活动周期，2 每日
				receiveDeadline:null,//领取期限
				receiveAddress:null,//领取地址
				notes:null,//备注 
				giftsSort:null,//排序
				picUpload:FILE_UPLOAD,
				homeImageUrl:null,//图片
				giftsPicturesMd5:null,
				repeatRecord:sessionStorage.getItem('repeatRecord'),
				isLimitNum:false,//是否限制张数
				canGiveLimitType:true,
				isDetail:false,
				url:null,
				param:null,
				htmlType:0,
				repeatRecordContent:null,
				diffText:'与初录不一致',
				diffGiftsName:false,
				diffHomeImg:false,
				diffIsLimitNum:false,
				diffWin:false,
				diffGiveLimitType:false,
				diffDeadline:false,
				diffAddress:false,
				diffNotes:false,
				diffIsSingleIssue:false,
				// iselectDate:false,//是否选择了日期
				firstDate:this.$store.getters.getFirstCouponData,
				secDate:this.$store.getters.getSecCouponData,
				title:'',//标题
			}
		},
		created(){
			if(this.btnType == '1'){//修改
				this.url = UPDATE_GIFTS
				this.title = '修改礼品'
				this.isDetail = false
			}else if(this.btnType == '3'){//新增 
				this.url = ADD_GIFTS
				this.title = '新建礼品'
				this.isDetail = false
			}else if(this.btnType == '2'){//详情
				this.title = '礼品详情'
				this.isDetail = true
			}
		},
		mounted(){
			if(this.btnType != 3){
				this.getFirstData()
			}
		},
		methods: {
			getFirstData(){
				let id = this.firstDate[this.pos-1].id
				this.$fetch(FIND_GIFTS_BY_ID,{
					giftsId:id
				})
					.then(res=>{
						if(res.status == 1){
							let data = res.data
							this.repeatRecordContent = res.data
							if(res.data){
								if(this.repeatRecord == 0){
									this.updataData(data)
								}else{
									// this.updataData(data)
									this.getSecData()
									if(this.repeatRecord == 1){
										this.diffGiveLimitType = res.data.giveLimitType != '0'
									}
								}
							}
						}else{
							this.$message({
								message: res.data,
								type: 'warning'
							});
						}
					})
					.catch(err=>{
						console.log(err)
						this.$message({
							message: '获取失败',
							type: 'warning'
						});
					})
			},
			getSecData(){
				let id = this.secDate[this.pos-1].id
				this.$fetch(FIND_GIFTS_BY_ID,{
					giftsId:id
				})
					.then(res=>{
						if(res.status == 1){
							let data = res.data
							if(res.data){
								if(this.repeatRecord == 1){
									this.updataData(data)
								}else{
									// this.diffGiveLimitType = res.data.giveLimitType != '0'
								}
							}
						}else{
							this.$message({
								message: res.data,
								type: 'warning'
							});
						}
					})
					.catch(err=>{
						console.log(err)
						this.$message({
							message: '获取失败',
							type: 'warning'
						});
					})
			},
			updataData(data){
				if(data.giftsName){
					this.giftsName = data.giftsName
					this.homeImageUrl = data.giftsPicturesUrl
					this.giftsPicturesUrl = data.giftsPicturesUrl
					this.prizePutNumber = data.prizePutNumber
					this.winningProbability = data.winningProbability
					if(data.prizePutNumber > 0){
						this.isLimitNum = true
					}else{
						this.isLimitNum = false
					}
					this.giveFrequencyLimit = data.giveFrequencyLimit
					this.giveLimitType = data.giveLimitType+''
					this.receiveDeadline = data.receiveDeadline
					this.receiveAddress = data.receiveAddress
					this.notes = data.notes
					this.giftsSort = data.giftsSort
					this.singleIssue = data.singleIssue
				}
			},
			beforeAvatarUpload(file) {
				let name = file.name.split('.')
				const isJpg = name[name.length-1].toLowerCase() === 'jpg'|| name[name.length-1].toLowerCase() === 'png';

				// const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 1;

				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 1MB!');
				}
				if (!isJpg) {
					this.$message.error('只能上传jpg或png格式文件');
				}
				const isCh = /^[^\u4e00-\u9fa5]+$/.test(name[name.length-2]);
				if (!isCh) {
					this.$message.error('上传的文件名称不能有中文!');
				}
				return isLt2M && isJpg && isCh;
			},
			/**
			 * e Dom对象
			 * w 位数
			 * ws 小数位数
			 * min 最小值
			 */
			checkNum(e,w,ws,min){
				let val = Number($(e.target).val())
				if(val < Math.pow(10,w) && val > 0){
					if(ws){
						$(e.target).val(val.toFixed(ws))
					}else{
						$(e.target).val(Math.floor(val))
					}
				}else{
					$(e.target).val(min)
					this.$message({
						message: `请输入1~${w}位正${ws == 0?'整':''}数`,
						type: 'warning'
					});
				}
			},
			homeImgSuccess(res, file) {
				this.homeImageUrl = res.url;
				// this.homeImageUrl = URL.createObjectURL(file.raw);
				this.giftsPicturesUrl = res.url
				this.giftsPicturesMd5 = res.fileMD5
				this.$refs.homeImg.clearFiles()
			},
			closeAddGift(type) {
				if(type == 1){
					if(!this.isLimitNum){
						this.prizePutNumber = 0
					}

					if(this.giveLimitType == 0){
						this.giveFrequencyLimit = '0'
					}

					this.receiveDeadline = this.receiveDeadline
					let id = this.$store.getters.getCurrentLottery
					if(this.repeatRecord == 0){
						this.giftsSort = this.leng*1 + 1
					}else{
						this.giftsSort = this.pos
					}
					if(this.giftsName && this.giftsPicturesUrl && this.winningProbability && this.receiveDeadline && this.receiveAddress){
						if(this.giftsName.length < 2){
							this.$message({
								message: '奖项名称最少输入2个字符',
								type: 'warning'
							});
							return;
						}
						if(this.receiveAddress.length < 2){
							this.$message({
								message: '领取地址最少输入2个字符',
								type: 'warning'
							});
							return;
						}
						if(this.singleIssue == '' || this.singleIssue == null){
							this.$message.error('请输入单次发放数量');
							return;
						}else if(!this.checkNum1(Number(this.singleIssue))){
							this.$message.error('单次发放数量只能为不含小数的数字');
							return;
						}
						if(!this.checkNum1(Number(this.winningProbability))){
							this.$message.error('中奖概率只能为不含小数的数字');
							return;
						}
						let param = {
							activityCode:this.activityCode,
							giftsName:this.giftsName,
							giftsPicturesUrl:this.giftsPicturesUrl,
							prizePutNumber:this.prizePutNumber,
							winningProbability:this.winningProbability,
							giveFrequencyLimit:this.giveFrequencyLimit,
							giveLimitType:this.giveLimitType + '',
							receiveDeadline:this.receiveDeadline.toString(),
							receiveAddress:this.receiveAddress,
							notes:this.notes,
							giftsSort:this.giftsSort,
							effectiveType:'0',//礼品必选择日期范围
							lotteryId:id,
							repeatRecord:this.repeatRecord,
							giftsPicturesMd5:this.giftsPicturesMd5,
							singleIssue:this.singleIssue
						}
						if(this.btnType == '1'){//修改
							param.id = this.giftID
						}
						if(this.diffGiftsName || this.diffHomeImg || this.diffWin || this.diffIsLimitNum || this.diffGiveLimitType || this.diffDeadline || this.diffAddress || this.diffNotes || this.diffIsSingleIssue){
							param.isIdentical = 1
						}else{
							param.isIdentical = 0
						}
	
	
						this.$post(this.url,param)
						.then(res=>{
							if(res.status == 1){
								if(res.data == '礼品规则修改成功'){
									this.$emit('closeAddGift')
								}else{
									param.id = res.data
									Bus.$emit('addItem',{
										param:param,
										id:res.data,
									})
									this.$emit('closeAddGift')
								}
								// Bus.$emit('refreshList')
								Bus.$emit('refreshCoupon',this.$store.getters.getCurrentLottery)
	
							}else{
								this.$message({
									message: res.data,
									type: 'warning'
								});
							}
						})
						.catch(err=>{
							console.log(err)
							this.$message({
								message: '获取失败',
								type: 'warning'
							});
						})
					}else{
						this.$message({
							message: '必填项不能为空',
							type: 'error'
						});
					}
				}else{
					this.$emit('closeAddGift')
				}	
			},
			findDetail(){
				
			},
			checkGiveLimit(){
				if(this.repeatRecord == 1){
					if(this.giveLimitType == this.repeatRecordContent.giveLimitType && this.giveFrequencyLimit == this.repeatRecordContent.giveFrequencyLimit){
						this.diffGiveLimitType = false
					}else{
						this.diffGiveLimitType = true
					}
				}
			}
		},
		watch:{
			giftsName(val){
				this.diffGiftsName = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.giftsName
			},
			giftsPicturesMd5(val){
				this.diffHomeImg = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.giftsPicturesMd5
			},
			prizePutNumber(val){
				this.diffIsLimitNum = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.prizePutNumber
			},
			isLimitNum(val){
				if(!val){
					this.prizePutNumber = 0
				}else{
					this.prizePutNumber = this.prizePutNumber > 0 ? this.prizePutNumber:1
				}
			},
			winningProbability(val){
				this.diffWin = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.winningProbability
			},
			giveLimitType(val){
				if(val == 0){
					this.canGiveLimitType = true
					this.giveFrequencyLimit = ''
				}else{
					this.canGiveLimitType = false
					this.value2 = val + ''
					this.giveFrequencyLimit = this.giveFrequencyLimit > 1?this.giveFrequencyLimit:'1'
				}
				this.checkGiveLimit()
			},
			value2(val){
				this.giveLimitType =val+''
				this.checkGiveLimit()
			},
			giveFrequencyLimit(val){
				this.checkGiveLimit()
			},
			receiveDeadline(val){
				this.diffDeadline = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.receiveDeadline
			},
			receiveAddress(val){
				this.diffAddress = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.receiveAddress
			},
			notes(val){
				this.diffNotes = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.notes
			},
			singleIssue(val){
				this.diffIsSingleIssue = this.repeatRecord == 1 && this.repeatRecordContent && val != this.repeatRecordContent.singleIssue
			},
		},
		computed:{
			picData(){
				return {
					repeatRecord:this.repeatRecord,
					htmlType:this.htmlType
				}
			}
		}
	}
</script>

<style lang="less">
	.addGiftBox {
		input[type="file"]{
			display: none;
		}
		.newAct{
			margin-left: 10%;
		}
		.newAct .el-upload {
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
		}
		.newAct .el-upload:hover {
			border-color: #409EFF;
		}
		.avatar-uploader-icon {
			font-size: 28px;
			color: #8c939d;
			width: 155px;
			height: 156px;
			line-height: 156px;
			text-align: center;
		}
		.avatar {
			width: 100px;
			height: 100px;
			display: block;
		}	
		.wordBox {
			width: 40%;
		}
		.changeDiv {
			width: 92%;
			position: relative;
		}
		.alertText {
			width: 14%;
		}
		.setInput {
			width: 15%;
		}
		.unit {
			color: #2D3343;
			margin-left: 0.05rem;
		}
		.el-radio,
		.el-checkbox,.el-textarea {
			margin-left: 0.08rem;
			margin-right: 0.08rem;
		}
		.el-textarea{
			width:70%;
		}
	}
	// .addImg{
	// 	width:160px;
	// 	height:160px;
	// 	border:1px dashed rgba(169,208,255,1);
	// 	border-radius:6px;
	// 	margin-left:0.08rem;
	// 	text-align: center;
	// }
	// .changeAdd{
	// 	color:#A9D0FF;
	// 	font-size:0.4rem;
	// }
</style>